# -*- encoding: utf-8 -*-
import sys
import os

from socket import *
reload(sys)
sys.setdefaultencoding("utf-8")

def rc4(data, key):
    # if the data is a string, convert to hex format.
    if (type(data) is type("string")):
        tmpData = data
        data = []
        for tmp in tmpData:
            data.append(ord(tmp))

    # if the key is a string, convert to hex format.
    if (type(key) is type("string")):
        tmpKey = key
        key = []
        for tmp in tmpKey:
            key.append(ord(tmp))

    # the Key-Scheduling Algorithm
    x = 0
    box = list(range(256))
    for i in range(256):
        x = (x + box[i] + key[i % len(key)]) % 256
        box[i], box[x] = box[x], box[i]

    # the Pseudo-Random Generation Algorithm
    x = 0
    y = 0
    out = bytearray()
    for c in data:
        x = (x + 1) % 256
        y = (y + box[x]) % 256
        box[x], box[y] = box[y], box[x]
        out.append(c ^ box[(box[x] + box[y]) % 256])
    return out


def decryption(key, pack_file=None, dec_file=None, dir=None):
    '''信誉库数据包解密'''

    if pack_file is None:
        return;
    if dec_file is None:
        return;
    if dir is None:
        return;
    in_file=dir + '/' + pack_file;
    out_file=dir + '/' + dec_file;
    if os.path.isfile(in_file) and os.path.isfile(out_file):
        fin = open(in_file, "rb")
        fout = open(out_file, "wb")
        while 1:
            data = fin.read(256)
            if not data:
                break
            decrypt = rc4(data, key)
            fout.write(decrypt)
        fin.close()
        fout.close()
        os.system("tar -xzvf %s -C %s" % (out_file, dir))


if __name__ == '__main__':
    if len(sys.argv) >= 5:
        decryption(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
        exit(0)
